import { Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Users } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users)
    private usersRepository: Repository<Users>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<Users> {
    try {
      const salt = await bcrypt.genSalt();
      const hashedPassword = await bcrypt.hash(createUserDto.pcpwd, salt);
      const newUser = this.usersRepository.create({
        ...createUserDto,
        pcpwd: hashedPassword,
      });
      return this.usersRepository.save(newUser);
    } catch (error) {
      console.error('Error creating user:', error);
      throw new InternalServerErrorException();
    }
  }

  async findOneByUserId(userid: string): Promise<Users | undefined> {
    try {
      console.log(`Querying user with userid: ${userid}`);
      const user = await this.usersRepository.findOne({ where: { userid } });
      if (!user) {
        return undefined;
      }
      console.log(`User found: ${JSON.stringify(user)}`);
      return user;
    } catch (error) {
      console.error('Error finding user by userid:', error);
      throw new InternalServerErrorException();
    }
  }

  async validateUser(userid: string, pcpwd: string): Promise<Users | null> {
    try {
      const user = await this.findOneByUserId(userid);
      if (!user) {
        return null;
      }
      const isPasswordValid = await bcrypt.compare(pcpwd, user.pcpwd);
      if (isPasswordValid) {
        return user;
      }
      return null;
    } catch (error) {
      console.error('Error validating user:', error);
      throw new InternalServerErrorException();
    }
  }
}
